import axios from 'axios'
import { showToast } from 'vant'

class Qinin {
  constructor(url) {
    this.url = url
    this.randowFileName = (file, directorUrl) => {
      console.log(file, file.type)
      let typeList = {
        "image/jpeg": ".jpg" ,
        "image/png": ".png"
      }
      const suffix = typeList[file.type] || '.jpg'
      const random = Array.from(Array(Number(24)), () => Math.floor(Math.random() * 36).toString(36)).join('')
      return `${directorUrl}/${random}${suffix}`
    }
  }
  
  Upload(token, host, file_path, fileinfo) {
    if (!token) {
      showToast('上传token缺失')
      return
    }
    const  file = fileinfo
    var formData = new FormData()
    formData.append('key', this.randowFileName(fileinfo, file_path))
    formData.append('file', file)
    formData.append('token', token)
    // 上传
    return new Promise((resolve, reject) => {
      axios.post('http://up-z1.qiniup.com', formData, {
        headers: {
          'Content-Type': 'multipart/form-data'
        },
      }).then(async(res) => {
        console.log(res, '上传成功')
        resolve(host + res.data.key)
      }).catch(err => {
        console.log(err, 'err11')
        reject(err)
      })
    })
  }
}
export default new Qinin()

